package com.im.partchat.db.dao;

import com.im.partchat.bean.Department;
import com.im.partchat.bean.Department_Table;
import com.im.partchat.db.PartChatDataBase;
import com.raizlabs.android.dbflow.config.DatabaseDefinition;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.Delete;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction;
import com.raizlabs.android.dbflow.structure.database.transaction.Transaction;

import java.util.List;

/**
 * Created by hhz on 2017/6/29.
 */

public class DeptDao {
    private static final DeptDao deptDao = new DeptDao();
    private DeptDao() {}
    public static DeptDao getInstance() {
        return deptDao;
    }
    public void saveAll(List<Department> departmentList) {
        Delete.table(Department.class);
        DatabaseDefinition database = FlowManager.getDatabase(PartChatDataBase.class);
        FastStoreModelTransaction<Department> fastStoreModelTransaction = FastStoreModelTransaction
                .insertBuilder(FlowManager.getModelAdapter(Department.class))
                .addAll(departmentList)
                .build();
        Transaction transaction = database.beginTransactionAsync(fastStoreModelTransaction).build();
        transaction.execute();
    }

    /**
     * 获取所有单位
     * @return
     */
    public List<Department> getAllDepart() {
        return SQLite.select().from(Department.class)
                .queryList();
    }

    /**
     * 根据ID获取单位
     * @param departId
     * @return
     */
    public Department getDepartment(String departId) {
        return SQLite.select().from(Department.class)
                .where(Department_Table.depet_id.eq(departId))
                .querySingle();
    }

    /**
     * 获取当前ID下的子部门
     * @param parentId
     * @return
     */
    public List<Department> getSubDepart(String parentId) {
        return SQLite.select().from(Department.class)
                .where(Department_Table.parentId.eq(parentId))
                .queryList();
    }

    /**
     * 获取顶级单位
     * @return
     */
    public List<Department> getFirstLevelDept() {
        return SQLite.select().from(Department.class)
                .where(Department_Table.parentId.eq("0"))
                .queryList();
    }
}
